﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int port = 2000;
                string host = "127.0.0.1";

                //创建终结点
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);

                //创建socket并连接到服务器
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Console.WriteLine("connecting...");
                socket.Connect(ipe);

                //向服务器发送信息
                string send = "hello,this is a socket test";
                byte[] bytes = Encoding.ASCII.GetBytes(send);

                Console.WriteLine("send message");
                socket.Send(bytes, bytes.Length, 0);

                //接受服务器返回的信息
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bl = socket.Receive(recvBytes, recvBytes.Length, 0);
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bl);
                Console.WriteLine($"client get message:{recvStr}");

                socket.Close();
                Console.ReadKey();
            }
            catch (ArgumentException e)
            {
                Console.WriteLine($"{nameof(ArgumentException)}:{e.Message}");
            }
            catch (SocketException e)
            {
                Console.WriteLine($"{nameof(SocketException)}:{e.Message}");
            }
        }
    }
}
